#include "Dev_manage.h"

#include "eeprom.h"
#include "Protocol_CAN.h"
#include "uds_port.h"

#define NODE_ID_INDEX (VM_INDEX_DEV_ID) // TODO: Modify
uint8_t                cur_node_id = 0;
uint8_t                data_format = 0;
Res2Press_Conversion_t res_conv_data[COLUMN_MAX];

uint8_t Dev_GetNodeID(void)
{ //
    return cur_node_id;
}

// TODO:从falsh里更新Node_ID
uint8_t Dev_ReadNodeID(uint8_t *dat)
{ // 若无，则为0 ，若有，则返回对应ID
    uint16_t data = 0;
    if (2 == VME2P_Read(VM_INDEX_DEV_ID, (uint8_t *)&data, 2)) {
        // 成功读取到数据
        cur_node_id = data & 0XF;
    }
    else {
        Dev_WriteNodeID(0);
    }
    *dat = cur_node_id;
    return 1;
}

// TODO:从Flash里读取数据更新ID
uint8_t Dev_WriteNodeID(uint8_t id)
{ //
    uint16_t ret_val = 0;

    id &= 0XF;
    if (id == Dev_GetNodeID()) {
        // ID无改变
        return 1;
    }
    ret_val = VME2P_Write(NODE_ID_INDEX, &id, 2);
    if (ret_val != 1) {
        //
        ret_val = VME2P_Write(NODE_ID_INDEX, &id, 2);
    }

    // 写成功，初始化相关ID
    return (ret_val == 1);
    // TODO;更新ID数据
}

uint8_t Dev_DataInit()
{
    // 更新设备节点
    uint8_t  data;
    uint8_t  data_array[120];
    uint32_t ret_val = 0;

    Dev_ReadNodeID(&data);
    REQUEST_ID  = DIAG_ID_BASE + data;
    FUNCTION_ID = DIAG_FUNCTION_ID;
    RESPONSE_ID = DIAG_RESPON_ID_BASE + data;

    // 更新设备属性信息
    VME2P_Read(VM_INDEX_DATA_FORMAT, &data_format, 1);
    for (uint8_t i = 0; i < COLUMN_MAX; i++) {
        ret_val = VME2P_Read(VM_INDEX_POINT0 + i, data_array, VM_INDEX_POINT_LEN);
        if (ret_val == VM_INDEX_POINT_LEN) {
            memcpy(&res_conv_data[i], data_array + 14 * 6, sizeof(res_conv_data[0]));
        }
    }
}
